package org.duiduo.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.duiduo.constant.ResponseConstants;
import org.duiduo.exception.CustomException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 导出工具类
 *
 * @author liangze
 * @date 2021/9/24 17:31
 */
public class ExportUtil {

    /**
     * 写excel
     *
     * @return
     */
    public static void export(String fileName, HttpServletResponse response, List<Map<String, Object>> list) {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
        } catch (Exception e) {
            throw new CustomException(ResponseConstants.Resp_1.RESP_00.getCode(), ResponseConstants.Resp_1.RESP_00.getMessage());
        } finally {
            writer.close();
            IoUtil.close(System.out);
        }
    }

}
